#include "user.h"
#include <QCryptographicHash>
#include <QByteArray>

User::User()
    : m_id(0)
    , m_username("")
    , m_password("")
    , m_registerTime(QDateTime::currentDateTime())
{
}

User::User(int id, const QString &username, const QString &password, const QDateTime &registerTime)
    : m_id(id)
    , m_username(username)
    , m_password(encryptPassword(password))
    , m_registerTime(registerTime)
{
}

int User::getId() const
{
    return m_id;
}

QString User::getUsername() const
{
    return m_username;
}

QString User::getPassword() const
{
    return m_password;
}

QDateTime User::getRegisterTime() const
{
    return m_registerTime;
}

void User::setId(int id)
{
    m_id = id;
}

void User::setUsername(const QString &username)
{
    m_username = username;
}

void User::setPassword(const QString &password)
{
    m_password = encryptPassword(password);
}

void User::setHashedPassword(const QString &hashedPassword)
{
    // 从数据库读取时，直接设置已加密好的哈希值，避免二次加密
    m_password = hashedPassword;
}

void User::setRegisterTime(const QDateTime &registerTime)
{
    m_registerTime = registerTime;
}

QString User::encryptPassword(const QString &password)
{
    // 使用SHA256算法对密码进行加密
    QByteArray hash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256);
    return QString(hash.toHex());
}

bool User::validatePassword(const QString &inputPassword) const
{
    // 验证输入的密码是否与存储的加密密码匹配
    QString encryptedInput = encryptPassword(inputPassword);
    return encryptedInput == m_password;
}
